import com.lzy.netty.utils.CuratorConfig;
import com.lzy.netty.utils.JedisPoolUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Mytest {
    @Test
    public void testJedisPool(){
        String key = "lzy";
        Jedis jedis = JedisPoolUtils.getJedis();
        jedis.set(key,"hello jedis");
        String CacheValue = jedis.get(key);
        System.out.println(CacheValue);
    }


    @Test
    public void testGetNettyPort(){
        Integer nettyPort = selectPort(nettyDefaultPort);
        System.out.println(nettyPort);

    }
    public static final Integer nettyDefaultPort = 875; // 885 895 905 915
    public static final String initOnlineCount = "0"; // 初始在线人数
    public static Integer selectPort(Integer port){
        String portKey = "netty_port";
        Jedis jedis = JedisPoolUtils.getJedis();

        Map<String,String> portMap = jedis.hgetAll(portKey);
        //System.out.println(portMap);

        // 由于map中的key应该都是整数类型的port，所以先转换为整数后，再比对，使用string类型比对可能会出现问题
        List<Integer> portList = portMap.entrySet()
                                .stream()
                                .map(entry -> Integer.parseInt(entry.getKey()))
                                .collect(Collectors.toList());

        System.out.println(portList);

        Integer nettyPort = null;
        if(portList == null || portList.isEmpty()){
            jedis.hset(portKey,port.toString(),initOnlineCount);
            nettyPort = port;
        }else{
            Integer maxPort = portMap.entrySet()
                    .stream()
                    .map(entry -> Integer.parseInt(entry.getKey()))
                    .reduce((p1, p2) -> p1 > p2 ? p1 : p2)
                    .get();
            // 基于最大端口号计算新端口（假设步长为10）
            Integer newPort = maxPort + 10;
            jedis.hset(portKey, newPort.toString(), initOnlineCount);
            nettyPort = newPort;
        }
        return nettyPort;
    }


    @Test
    public void testCurator() throws Exception {
        CuratorFramework client = CuratorConfig.getClient();
        String path = "/abc";
        Stat stat = client.checkExists().forPath(path);
        String s = new String(client.getData().forPath(path));
        System.out.println(s);

    }
}
